/**
 * 
 */
package co.fitstart.data.handler.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.support.Result;
import com.demo2do.core.support.sms.handler.SmsHandler;
import com.demo2do.core.utils.StringUtils;

import co.fitstart.data.entity.MessageType;
import co.fitstart.data.handler.SmsSender;

/**
 * @author downpour
 *
 */
@Component("smsSender")
public class SmsSenderImpl implements SmsSender {
    
    private static final Logger logger = LoggerFactory.getLogger(SmsSender.class);
    
    @Autowired
    private SmsHandler smsHandler;

    @Value("#{config['sms.company']}")
    private String company;

    /* (non-Javadoc)
     * @see co.fitstart.mobile.handler.SmsSender#generateVerifyCode(java.lang.String)
     */
    public String generateVerifyCode(String mobile) {
        return RandomStringUtils.randomNumeric(6);
    }

    /* (non-Javadoc)
     * @see co.fitstart.mobile.handler.SmsSender#sendVerifyCode(java.lang.String, java.lang.String)
     */
    public boolean sendVerifyCode(String mobile, String code) {
        
        Result result = new Result();
        
        // Get message template
        String template = smsHandler.getShortMessageTemplate(MessageType.VERIFY_CODE);
        
        if (template != null) {
            
            Map<String, String> values = new HashMap<String, String>(2);
            values.put("company", company);
            values.put("code", code);
            
            String message = StringUtils.replacePlaceHolder(template, values, "#", "#");
            
            logger.trace("#onSendVerifyCode - sending verify code to mobile: [{}], verify code is: [{}]", mobile, code);
            
            // Send message by calling sms handler
            result = smsHandler.sendShortMessage(mobile, message);
            
        }
        
        return result.isValid();
        
    }
    
    /* (non-Javadoc)
     * @see co.fitstart.mobile.handler.SmsSender#checkVerifyCode(java.lang.String, java.lang.String, java.lang.String)
     */
    public boolean checkVerifyCode(String mobile, String code, String token) {
        String vtoken = DigestUtils.sha256Hex(StringUtils.connect(mobile, code, "fitstart"));
        return org.apache.commons.lang3.StringUtils.equals(vtoken, token);
    }

}
